'use strict';
(function () {
    var socket;


    var is = {
        isRectangle: true,

        set: function (shape) {
            var cache = this;
            cache.isRectangle = true;
            cache['is' + shape] = true;
        }
    };

    function addEvent(element, eventType, callback) {
        if (element.addEventListener) {
            element.addEventListener(eventType, callback, !1);
            return true;
        } else if (element.attachEvent) {
            return element.attachEvent('on' + eventType, callback);
        } else {
            element['on' + eventType] = callback;
        }
        return this;
    }

    function preventStopEvent(e) {
        if (!e) {
            return;
        }

        if (typeof e.preventDefault === 'function') {
            e.preventDefault();
        }

        if (typeof e.stopPropagation === 'function') {
            e.stopPropagation();
        }
    }

    //get element by id
    function find(selector) {
        return document.getElementById(selector);
    }

    var points = [],
        textarea = find('code-text'),
        lineWidth = 2,
        strokeStyle = '#6c96c8',
        fillStyle = 'transparent',
        globalAlpha = 1,
        globalCompositeOperation = 'source-over',
        lineCap = 'round',
        font = '15px "Arial"',
        lineJoin = 'round';

    function getContext(id) {
        var canv = find(id),
            ctx = canv.getContext('2d');

        canv.setAttribute('width', innerWidth);
        canv.setAttribute('height', innerHeight);

        ctx.lineWidth = lineWidth;
        ctx.strokeStyle = strokeStyle;
        ctx.fillStyle = fillStyle;
        ctx.font = font;

        return ctx;
    }

    var context = getContext('main-canvas'),
        tempContext = getContext('temp-canvas');

    var drawHelper = {
        redraw: function () {
            tempContext.clearRect(0, 0, innerWidth, innerHeight);
            context.clearRect(0, 0, innerWidth, innerHeight);

            var i, point, length = points.length;
            for (i = 0; i < length; i++) {
                point = points[i];
                if (point && point.length && this[point[0]]) {
                    this[point[0]](context, point[1], point[2]);
                }
                // else warn
            }
        },
        getOptions: function (opt) {
            opt = opt || {};
            return [
                opt.lineWidth || lineWidth,
                opt.strokeStyle || strokeStyle,
                opt.fillStyle || fillStyle,
                opt.globalAlpha || globalAlpha,
                opt.globalCompositeOperation || globalCompositeOperation,
                opt.lineCap || lineCap,
                opt.lineJoin || lineJoin,
                opt.font || font
            ];
        },
        handleOptions: function (context, opt, isNoFillStroke) {
            opt = opt || this.getOptions();

            context.globalAlpha = opt[3];
            context.globalCompositeOperation = opt[4];

            context.lineCap = opt[5];
            context.lineJoin = opt[6];
            context.lineWidth = opt[0];

            context.strokeStyle = opt[1];
            context.fillStyle = opt[2];

            context.font = opt[7];

            if (!isNoFillStroke) {
                context.stroke();
                context.fill();
            }
        },
        rect: function (context, point, options) {
            this.handleOptions(context, options, true);

            context.strokeRect(point[0], point[1], point[2], point[3]);
            context.fillRect(point[0], point[1], point[2], point[3]);
        }
    };


    var rectHandler = {
        ismousedown: false,
        prevX: 0,
        prevY: 0,

        mouseDownHandler:function(data){
            console.log("data="+data);
            var x = data.x - canvas.offsetLeft,
                y = data.y - canvas.offsetTop;


            var t = this;

            t.prevX = x;
            t.prevY = y;

            t.ismousedown = true;
        },

        mouseUpHandler: function(data){
            console.log("data="+data);

            var x = data.x - canvas.offsetLeft,
                y = data.y - canvas.offsetTop;

            var t = this;
            if (t.ismousedown) {
                points[points.length] = ['rect', [t.prevX, t.prevY, x - t.prevX, y - t.prevY], drawHelper.getOptions()];

                t.ismousedown = false;
            }
        },

        mouseMoveHandler:function(data){
            console.log("data="+data);
            var x = data.x - canvas.offsetLeft,
                y = data.y - canvas.offsetTop;

            var t = this;
            if (t.ismousedown) {
                tempContext.clearRect(0, 0, innerWidth, innerHeight);

                drawHelper.rect(tempContext, [t.prevX, t.prevY, x - t.prevX, y - t.prevY]);
            }
        },

        mousedown: function (e,data) {
            console.log("mousedown------");
            if(data==undefined){
                data = new Object();
                data.x=0;
                data.y=0;
            }

            console.log("data="+data);
            var x = data.x - canvas.offsetLeft,
                y = data.y - canvas.offsetTop;


            var t = this;

            t.prevX = x;
            t.prevY = y;

            t.ismousedown = true;

        },
        mouseup: function (e,data) {
            console.log("mouseup------");
            if(data==undefined){
                data = new Object();
                data.x=0;
                data.y=0;
            }
            console.log("data="+data);

            var x = data.x - canvas.offsetLeft,
                y = data.y - canvas.offsetTop;

            var t = this;
            if (t.ismousedown) {
                points[points.length] = ['rect', [t.prevX, t.prevY, x - t.prevX, y - t.prevY], drawHelper.getOptions()];

                t.ismousedown = false;
            }

        },
        mousemove: function (e, data) {
            console.log("mousemove------");
            if(data==undefined){
                data = new Object();
                data.x=0;
                data.y=0;
            }

            console.log("data="+data);
            var x = data.x - canvas.offsetLeft,
                y = data.y - canvas.offsetTop;

            var t = this;
            if (t.ismousedown) {
                tempContext.clearRect(0, 0, innerWidth, innerHeight);

                drawHelper.rect(tempContext, [t.prevX, t.prevY, x - t.prevX, y - t.prevY]);
            }
        }
    };

    var canvas = tempContext.canvas;

    // addEvent(canvas, 'mousedown', function (e) {
    //     var cache = is;
    //     rectHandler.mousedown(e)
    //     drawHelper.redraw();
    //     preventStopEvent(e);
    // });
    //
    // addEvent(canvas, 'mousemove', function (e) {
    //     var cache = is;
    //     rectHandler.mousemove(e);
    //     preventStopEvent(e);
    // });
    //
    // addEvent(canvas, 'mouseup', function(e) {
    //
    //     rectHandler.mouseup(e);
    //     var cache = is;
    //     drawHelper.redraw();
    //
    //     // syncPoints(is.isDragAllPaths || is.isDragLastPath ? true : false);
    //
    //     preventStopEvent(e);
    // });

    if (typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        console.log("您的浏览器支持WebSocket");
        socket = new WebSocket("ws://localhost:8050/schoolms/draw");
        //打开事件
        socket.onopen = function () {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function (msg) {

            if(msg.data !="connected") {
                var data = JSON.parse(msg.data);
                var action = data.action;
                if(action==="mousemove"){
                    rectHandler.mouseMoveHandler(data);
                    preventStopEvent(e);
                    // console.log("$(canvas)="+$(canvas));
                    // canvas.addEventListener("mousemove", callback, !1);
                    // rectHandler.mouseMoveHandler(data);
                    // canvas.addEventListener("mousemove", function () {
                    //     rectHandler.mouseMoveHandler(data);
                    // }, !1);
                    // $(canvas).trigger("mousemove");
                }else if(action==="mousedown"){
                    rectHandler.mouseDownHandler(data);
                    drawHelper.redraw();
                    preventStopEvent(e);
                    // canvas.onmousedown = function (ev) {
                    //     rectHandler.mouseDownHandler(data);
                    // }
                    // $(canvas).trigger("mousedown");
                    // canvas.addEvent("mousedown",function () {
                    //     rectHandler.mouseDownHandler(data);
                    // });
                    // var evt  = document.createEvent("MouseEvents");
                    // evt.initEvent("mousedown",false,false);
                    // canvas.dispatchEvent(evt);
                    // canvas.addEventListener("mousedown", function () {
                    //     rectHandler.mouseDownHandler(data);
                    // }, !1);
                    // canvas.mousedown();

                }else if(action==="mouseup"){
                    rectHandler.mouseUpHandler(data);
                    drawHelper.redraw();
                    preventStopEvent(e);
                    // canvas.addEventListener("mouseup", function () {
                    //     rectHandler.mouseUpHandler(data);
                    // }, !1);
                    // $(canvas).trigger("mouseup");
                }
                // console.log(data.action);
            }
            //发现消息进入    调后台获取
            // getCallingList();
        };
        //关闭事件
        socket.onclose = function () {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
            alert("Socket发生了错误");
        }
    }
})();